class AIAssistant:
    """AI助手父类，定义基础属性"""

    def __init__(self, aid, name, assistant_type, version, online, score):
        self.aid = aid  # 编号（ID）
        self.name = name  # 名称
        self.type = assistant_type  # 类型
        self.version = version  # 版本号
        self.online = online  # 是否在线
        self.score = score  # 能力评分

    def display_info(self):
        """显示助手基本信息"""
        status = "在线" if self.online else "离线"
        status_icon = "🟢在线" if self.online else "🔴离线"
        return f"ID: {self.aid}, 名称: {self.name}, 类型: {self.type}, 版本: {self.version}, 状态: {status_icon}, 能力评分: {self.score} [{self.type}]"

    def start_service(self):
        """启动助手服务"""
        if self.online:
            return False, f"助手【{self.name}】已在运行。"
        self.online = True
        return True, f"✅ 助手【{self.name}】已启动。"

    def stop_service(self):
        """停止助手服务"""
        if not self.online:
            return False, f"助手【{self.name}】已停止。"
        self.online = False
        return True, f"✅ 助手【{self.name}】已停止。"

    def assign_task(self, task_content):
        """分配任务给助手"""
        if not self.online:
            return False, f"❌ {self.name} 当前离线，无法执行任务。"
        return True, f"✅ 已为【{self.name}】分配任务：{task_content}"


class DataAnalysisAssistant(AIAssistant):
    """数据分析助手子类"""

    def __init__(self, aid, name, version, online, score, specialty=None):
        super().__init__(aid, name, "数据分析助手", version, online, score)
        self.specialty = specialty or "通用数据分析"

    def display_info(self):
        """显示数据分析助手的详细信息"""
        basic_info = super().display_info()
        return f"{basic_info}, 专长: {self.specialty}"


class ImageGenerationAssistant(AIAssistant):
    """图片生成助手子类"""

    def __init__(self, aid, name, version, online, score, resolution=None):
        super().__init__(aid, name, "图片生成助手", version, online, score)
        self.resolution = resolution or "1024x1024"

    def display_info(self):
        """显示图片生成助手的详细信息"""
        basic_info = super().display_info()
        return f"{basic_info}, 最高分辨率: {self.resolution}"


class TextGenerationAssistant(AIAssistant):
    """文本生成助手子类"""

    def __init__(self, aid, name, version, online, score, max_length=None):
        super().__init__(aid, name, "文本生成助手", version, online, score)
        self.max_length = max_length or "无限"

    def display_info(self):
        """显示文本生成助手的详细信息"""
        basic_info = super().display_info()
        return f"{basic_info}, 最大生成长度: {self.max_length}"


class TranslationAssistant(AIAssistant):
    """翻译助手子类"""

    def __init__(self, aid, name, version, online, score, languages=None):
        super().__init__(aid, name, "翻译助手", version, online, score)
        self.languages = languages or "中英互译"

    def display_info(self):
        """显示翻译助手的详细信息"""
        basic_info = super().display_info()
        return f"{basic_info}, 支持语言: {self.languages}"


class VoiceAssistant(AIAssistant):
    """语音助手子类"""

    def __init__(self, aid, name, version, online, score, voice_type=None):
        super().__init__(aid, name, "语音助手", version, online, score)
        self.voice_type = voice_type or "标准"

    def display_info(self):
        """显示语音助手的详细信息"""
        basic_info = super().display_info()
        note = "(注意：这些模型主要为文本交互，语音功能多由小爱同学、小薇等专属语音助手集成调用)"
        return f"{basic_info}, 语音类型: {self.voice_type} {note}"


class AIManager:
    """AI助手管理器类，用于管理所有AI助手"""

    def __init__(self, capacity=100):
        self.capacity = capacity  # 最大容量
        self.assistants = []  # 存储助手信息的列表
        # 初始化一些默认助手数据
        self._initialize_default_assistants()

    def _initialize_default_assistants(self):
        """初始化默认的AI助手数据"""
        default_assistants = [
            VoiceAssistant(101, "小智", "v1.2", True, 85, "男声"),
            TextGenerationAssistant(102, "文小助", "v2.0", True, 92, "8000字符"),
            ImageGenerationAssistant(103, "图灵", "v1.5", False, 88, "4K"),
            DataAnalysisAssistant(104, "数小析", "v1.0", True, 79, "商业数据分析"),
            TranslationAssistant(105, "翻译精灵", "v2.1", False, 95, "多语言支持")
        ]
        self.assistants.extend(default_assistants)

    def find_assistant_by_id(self, aid):
        """根据ID查找助手"""
        for assistant in self.assistants:
            if assistant.aid == aid:
                return assistant
        return None

    def add_assistant(self, assistant):
        """添加新的AI助手"""
        if len(self.assistants) >= self.capacity:
            return False, "❌ 系统容量已满，无法添加新助手。"

        if self.find_assistant_by_id(assistant.aid):
            return False, f"❌ ID {assistant.aid} 已存在，请使用其他ID。"

        self.assistants.append(assistant)
        return True, f"✅ 助手【{assistant.name}】添加成功！"

    def delete_assistant(self, aid):
        """删除AI助手（按ID）"""
        assistant = self.find_assistant_by_id(aid)
        if not assistant:
            return False, f"❌ 未找到ID为 {aid} 的助手。"

        self.assistants.remove(assistant)
        return True, f"✅ 助手【{assistant.name}】已删除。"

    def update_assistant(self, aid, attribute, value):
        """根据ID修改助手信息"""
        assistant = self.find_assistant_by_id(aid)
        if not assistant:
            return False, f"❌ 未找到ID为 {aid} 的助手。"

        # 检查属性是否可修改
        if attribute == "name":
            assistant.name = value
        elif attribute == "type":
            # 类型修改需要重新创建实例，这里简化处理
            assistant.type = value
        elif attribute == "version":
            assistant.version = value
        elif attribute == "online":
            assistant.online = bool(int(value))
        elif attribute == "score":
            try:
                score = float(value)
                if 0 <= score <= 100:
                    assistant.score = score
                else:
                    return False, "❌ 能力评分必须在0-100之间。"
            except ValueError:
                return False, "❌ 能力评分必须是数字。"
        else:
            return False, f"❌ 不支持修改属性: {attribute}"

        return True, f"✅ 助手【{aid}】修改成功！"

    def list_all_assistants(self):
        """查看所有AI助手列表"""
        if not self.assistants:
            return "❌ 暂无助手信息。"

        result = "所有AI助手列表：\n"
        for i, assistant in enumerate(self.assistants, 1):
            status = "在线" if assistant.online else "离线"
            result += f"{i}. ID: {assistant.aid}, 名称: {assistant.name}, 类型: {assistant.type}, 版本: {assistant.version}, 状态: {status}, 能力评分: {assistant.score} [{assistant.type}]\n"
        return result

    def get_statistics(self):
        """显示系统统计信息"""
        total = len(self.assistants)
        online_count = sum(1 for assistant in self.assistants if assistant.online)
        offline_count = total - online_count
        avg_score = sum(assistant.score for assistant in self.assistants) / total if total > 0 else 0

        result = "\n系统统计信息：\n"
        result += f"总助手数: {total}\n"
        result += f"在线助手数: {online_count}\n"
        result += f"离线助手数: {offline_count}\n"
        result += f"平均能力评分: {avg_score:.2f}\n"
        return result


def main():
    """主函数，运行AI助手管理器"""
    manager = AIManager()

    while True:
        print("\n========== 🤖AI助手管理器 ==========")
        print("1. 查看所有AI助手列表")
        print("2. 根据ID查询助手详情")
        print("3. 添加新的AI助手")
        print("4. 根据ID修改助手信息")
        print("5. 删除AI助手（按ID）")
        print("6. 启动AI助手服务")
        print("7. 停止AI助手服务")
        print("8. 为AI助手分配任务")
        print("9. 显示系统统计信息")
        print("0. 退出系统")
        print("===================================")

        try:
            choice = int(input("请选择操作: "))

            if choice == 0:
                print("感谢使用AI助手管理器，再见！")
                break

            elif choice == 1:
                print(manager.list_all_assistants())

            elif choice == 2:
                aid = int(input("请输入要查询的AI助手ID: "))
                assistant = manager.find_assistant_by_id(aid)
                if assistant:
                    print(f"✅ 查询结果: {assistant.display_info()}")
                else:
                    print(f"❌ 未找到ID为 {aid} 的助手。")

            elif choice == 3:
                print("添加新AI助手")
                try:
                    aid = int(input("请输入ID: "))
                    name = input("请输入名称: ")

                    # 选择助手类型
                    print("请选择助手类型:")
                    print("1. 数据分析助手")
                    print("2. 图片生成助手")
                    print("3. 文本生成助手")
                    print("4. 翻译助手")
                    print("5. 语音助手")
                    type_choice = int(input("请选择类型(1-5): "))

                    version = input("请输入版本号: ")
                    online = bool(int(input("是否在线？(1-是, 0-否): ")))
                    score = float(input("请输入能力评分(0-100): "))

                    # 根据类型创建相应的助手实例
                    if type_choice == 1:
                        specialty = input("请输入专长(可选，直接回车跳过): ") or None
                        assistant = DataAnalysisAssistant(aid, name, version, online, score, specialty)
                    elif type_choice == 2:
                        resolution = input("请输入最高分辨率(可选，直接回车跳过): ") or None
                        assistant = ImageGenerationAssistant(aid, name, version, online, score, resolution)
                    elif type_choice == 3:
                        max_length = input("请输入最大生成长度(可选，直接回车跳过): ") or None
                        assistant = TextGenerationAssistant(aid, name, version, online, score, max_length)
                    elif type_choice == 4:
                        languages = input("请输入支持语言(可选，直接回车跳过): ") or None
                        assistant = TranslationAssistant(aid, name, version, online, score, languages)
                    elif type_choice == 5:
                        voice_type = input("请输入语音类型(可选，直接回车跳过): ") or None
                        assistant = VoiceAssistant(aid, name, version, online, score, voice_type)
                    else:
                        print("❌ 无效的类型选择，默认为文本生成助手")
                        assistant = TextGenerationAssistant(aid, name, version, online, score)

                    success, message = manager.add_assistant(assistant)
                    print(message)
                except ValueError:
                    print("❌ 输入格式错误，请检查您的输入。")

            elif choice == 4:
                print("修改AI助手数据")
                try:
                    aid = int(input("请输入ID: "))
                    assistant = manager.find_assistant_by_id(aid)
                    if not assistant:
                        print(f"❌ 未找到ID为 {aid} 的助手。")
                        continue

                    print("可修改属性列表为：name,type,version,online,score")
                    input_str = input("请输入要要修改的属性和值，用空格分割: ")
                    parts = input_str.strip().split(" ")
                    if len(parts) < 2:
                        print("❌ 输入格式错误，请使用'属性 值'格式。")
                        continue

                    attribute = parts[0].lower()
                    value = " ".join(parts[1:])

                    success, message = manager.update_assistant(aid, attribute, value)
                    print(message)
                except ValueError:
                    print("❌ 输入格式错误，请检查您的输入。")

            elif choice == 5:
                try:
                    aid = int(input("请输入要删除的AI助手ID: "))
                    success, message = manager.delete_assistant(aid)
                    print(message)
                except ValueError:
                    print("❌ 请输入有效的ID。")

            elif choice == 6:
                try:
                    aid = int(input("请输入要启动的AI助手ID: "))
                    assistant = manager.find_assistant_by_id(aid)
                    if not assistant:
                        print(f"❌ 未找到ID为 {aid} 的助手。")
                        continue

                    success, message = assistant.start_service()
                    print(message)
                except ValueError:
                    print("❌ 请输入有效的ID。")

            elif choice == 7:
                try:
                    aid = int(input("请输入要停止的AI助手ID: "))
                    assistant = manager.find_assistant_by_id(aid)
                    if not assistant:
                        print(f"❌ 未找到ID为 {aid} 的助手。")
                        continue

                    success, message = assistant.stop_service()
                    print(message)
                except ValueError:
                    print("❌ 请输入有效的ID。")

            elif choice == 8:
                try:
                    aid = int(input("请输入目标AI助手ID: "))
                    assistant = manager.find_assistant_by_id(aid)
                    if not assistant:
                        print(f"❌ 未找到ID为 {aid} 的助手。")
                        continue

                    task_content = input("请输入任务内容: ")
                    success, message = assistant.assign_task(task_content)
                    print(message)
                except ValueError:
                    print("❌ 请输入有效的ID。")

            elif choice == 9:
                print(manager.get_statistics())

            else:
                print("❌ 无效的选择，请重新输入。")

        except ValueError:
            print("❌ 请输入有效的数字选项。")
        except Exception as e:
            print(f"❌ 发生错误: {e}")


if __name__ == "__main__":
    main()